package com.zxl.yjb.activity.home.sharemessage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.district.DistrictResult;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.position.PositionActivity;
import com.zxl.yjb.activity.payfee.ShareMessagePayFeeActivity;
import com.zxl.yjb.adapter.HorizontalImageAdapter;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.AreaBean;
import com.zxl.yjb.bean.CouponBean;
import com.zxl.yjb.bean.DiscountAmountBean;
import com.zxl.yjb.bean.FileUploadBean;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.ShareMessageResponseBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.GetPositionUtil;
import com.zxl.yjb.utils.PickerViewUtils;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.TestAddressProvider;
import com.zxl.yjb.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.AddressSelector;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

public class MessagePublishActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.tv_service_type)
    TextView tv_service_type;
    @BindView(R.id.tv_publish_time)
    TextView tv_publish_time;
    @BindView(R.id.tv_position)
    TextView tv_position;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_confirm)
    TextView tv_confirm;
    @BindView(R.id.rv_pic_list)
    RecyclerView rv_pic_list;
    @BindView(R.id.tv_publish)
    TextView tv_publish;
    @BindView(R.id.iv_add_pic)
    ImageView iv_add_pic;
    @BindView(R.id.ll_add_pic)
    LinearLayout ll_add_pic;
    @BindView(R.id.tv_phone)
    TextView tv_phone;

    private DataManager dataManager;

    private static final int REQUEST_TYPE = 111;
    private static final int REQUEST_POSITION = 112;
    private static final int REQUEST_TITLE = 113;
    private static final int REQUEST_DESCRIBE = 114;
    private static final int REQUEST_PHONE = 115;

    private LocationBean locationBean;
    private ArrayList<DiscountAmountBean> dayPriceList = new ArrayList<>();
    private ArrayList<String> dayList = new ArrayList<>();
    private List<LocalMedia> selectList = new ArrayList<>();//选择图片路径
    private HorizontalImageAdapter adapter;

    private int topicid;
    private String duration = "";
    private double lon;
    private double lat;
    private String Country = "";
    private String Province = "";
    private String City = "";
    private String district = "";
    private String street = "";
    private String payment = "";
    private String payment_cal = "";
    private String title = "";
    private String content = "";
    private String imgs = "";
    private String phone = "";

    /*总余额*/
    private String topic_amount = "";
    /*折扣金额*/
    private String dec_per_topic = "";
    /*折扣标准*/
    private String action_topic_low_throughout = "";


    private List<AreaBean> provinceList = new ArrayList<>();
    private ObserverOnNextListener<List<AreaBean>> observerOnNextListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_pubish);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initDefaultLocation();
        initView();
        getVoucherList();
    }

    @Override
    protected void initView() {
        tv_page_title.setText("发布信息");
//        tv_position.setText(street);

        LinearLayoutManager manager = new LinearLayoutManager(MessagePublishActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_pic_list.setLayoutManager(manager);
        HorizontalImageAdapter.onAddPicClickListener onAddPicClickListener = new HorizontalImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick(View view) {
                DisplayUtil.openAlbum(MessagePublishActivity.this, 8, selectList, PictureConfig.CHOOSE_REQUEST);
            }
        };
        adapter = new HorizontalImageAdapter(MessagePublishActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(8);
        rv_pic_list.setAdapter(adapter);
    }

    private void getVoucherList() {

        DataManager dataManager = new DataManager();
        ObserverOnNextListener<CouponBean> listener = new ObserverOnNextListener<CouponBean>() {
            @Override
            public void onNext(CouponBean couponBean) {
                topic_amount = couponBean.getVoucher().getTopic_amount();
                dec_per_topic = couponBean.getVoucher_rule().getDec_per_topic()+"";
                action_topic_low_throughout = couponBean.getVoucher_rule().getAction_topic_low_throughout()+"";
            }
        };
        dataManager.voucherList(new ProgressObserver<CouponBean>(listener, this));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            switch (requestCode) {
            	case REQUEST_TYPE:
                    topicid = data.getIntExtra("id",0);
                    tv_service_type.setText(data.getStringExtra("name"));
            		break;
            	case REQUEST_POSITION:
                    PoiItem poiItem = data.getParcelableExtra("position");
                    if (poiItem!=null)
                        tv_position.setText(poiItem.getTitle());
                        lon = poiItem.getLatLonPoint().getLongitude();
                        lat = poiItem.getLatLonPoint().getLatitude();
            		break;
            	case REQUEST_TITLE:
                    title = data.getStringExtra("content");
                    tv_title.setText("已经输入字数"+title.length());
            		break;
            	case REQUEST_DESCRIBE:
                    content = data.getStringExtra("content");
                    tv_content.setText("已经输入字数"+content.length());
            		break;
            	case REQUEST_PHONE:
                    phone = data.getStringExtra("content");
                    tv_phone.setText(phone);
            		break;
                case PictureConfig.CHOOSE_REQUEST: // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //刷新图片列表；
                    ll_add_pic.setVisibility(View.GONE);
                    rv_pic_list.setVisibility(View.VISIBLE);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;

            	default:
            		break;
            }
        }
    }

    private void initDefaultLocation()
    {
        locationBean = (LocationBean) SaveBeanUtil.getBean(this, Const.LOCATION_LNGLAT);
        if (locationBean != null) {
            lon = locationBean.getLng();
            lat = locationBean.getLat();
            /*Country = locationBean.getCountry();
            Province = locationBean.getProvince();
            City = locationBean.getCity();
            district = locationBean.getDistrict();
            street = locationBean.getStreet();*/
        }
    }

    private void uploadImage()
    {
        dataManager = new DataManager();
        ObserverOnNextListener<FileUploadBean> listener = new ObserverOnNextListener<FileUploadBean>() {
            @Override
            public void onNext(FileUploadBean fileUploadBean) {
                if (fileUploadBean.getUrls().size()>0)
                {
                    for (int i = 0; i < fileUploadBean.getUrls().size(); i++) {
                        imgs+=fileUploadBean.getUrls().get(i)+",";
                    }
                }
                publishData();
            }
        };
        dataManager.uploadMultiPicture(new ProgressObserver<FileUploadBean>(listener,this),selectList);
    }

    private void publishData()
    {
        dataManager = new DataManager();
        Map<String,String> map = new HashMap<>();
        map.put("topicid",topicid+"");
        map.put("duration",duration);
        map.put("lon",lon+"");
        map.put("lat",lat+"");
        map.put("country",Country);
        map.put("province",Province);
        map.put("city",City);
        map.put("district",district);
        map.put("street",street);
        map.put("payment",payment);
        map.put("money_amount",payment);
        map.put("money_amount_cal",payment_cal);
        map.put("title",title);
        map.put("content",content);
        map.put("imgs",imgs);
        map.put("phone",phone);
        ObserverOnNextListener<ShareMessageResponseBean> listener = new ObserverOnNextListener<ShareMessageResponseBean>() {
            @Override
            public void onNext(ShareMessageResponseBean shareMessageResponseBean) {
                if (!TextUtils.isEmpty(shareMessageResponseBean.getOrder_amount()))
                {
                    if (Double.parseDouble(shareMessageResponseBean.getOrder_amount()) == 0)
                    {
                        dataManager = new DataManager();
                        Map<String,String> map1 = new HashMap<>();
                        map1.put("order_id",shareMessageResponseBean.getOrder_id()+"");
                        map1.put("order_sn",shareMessageResponseBean.getOrder_sn());
                        map1.put("order_amount",shareMessageResponseBean.getOrder_amount());
                        ObserverOnNextListener<Object> listener1 = new ObserverOnNextListener<Object>() {
                            @Override
                            public void onNext(Object o) {
                                ToastUtils.show(MessagePublishActivity.this,"发布成功");
                                finish();
                            }
                        };
                        dataManager.freeTopicAction(new ProgressObserver<Object>(listener1,MessagePublishActivity.this),map1);
                    }
                    else
                    {
                        Intent intent = new Intent(MessagePublishActivity.this, ShareMessagePayFeeActivity.class);
                        intent.putExtra("order_id",shareMessageResponseBean.getOrder_id());
                        intent.putExtra("order_sn",shareMessageResponseBean.getOrder_sn());
                        intent.putExtra("money",shareMessageResponseBean.getOrder_amount());
                        intent.putExtra("money_cal",payment_cal);
                        startActivity(intent);
                    }
                }


            }
        };
        dataManager.publishShareMessage(new ProgressObserver<ShareMessageResponseBean>(listener,this),map);
    }

    private void getPrice()
    {
        dataManager = new DataManager();
        ObserverOnNextListener<ArrayList<DiscountAmountBean>> listener = new ObserverOnNextListener<ArrayList<DiscountAmountBean>>() {
            @Override
            public void onNext(ArrayList<DiscountAmountBean> discountAmountBeans) {
                dayPriceList.clear();
                dayPriceList.addAll(discountAmountBeans);
                dayList.clear();
                for (int i = 0; i < discountAmountBeans.size(); i++) {
                    dayList.add(discountAmountBeans.get(i).getDuration());
                }
                showPickDialog();
            }
        };
        dataManager.getFeeDiscountAmount(new ProgressObserver<ArrayList<DiscountAmountBean>>(listener,this),new HashMap<String,String>());
    }

    private void showPickDialog()
    {
        PickerViewUtils.customOptionPickerView(dayList, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tv_publish_time.setText(dayPriceList.get(options1).getDuration()+"天");
                duration = dayPriceList.get(options1).getDuration();
                payment = dayPriceList.get(options1).getAmount();
                if (!TextUtils.isEmpty(topic_amount)
                        &&!TextUtils.isEmpty(dec_per_topic)
                        &&!TextUtils.isEmpty(action_topic_low_throughout))
                {
                    if (Double.parseDouble(topic_amount)>Double.parseDouble(dec_per_topic)
                            &&Double.parseDouble(dayPriceList.get(options1).getAmount())>Double.parseDouble(action_topic_low_throughout))
                    {
                        double pay = Double.parseDouble(dayPriceList.get(options1).getAmount())-Double.parseDouble(dec_per_topic);
                        if (pay<0)
                        {
                            payment_cal = "0";
                        }
                        else
                        {
                            payment_cal = pay+"";
                        }
                        tv_money.setText(dayPriceList.get(options1).getAmount()+"元"+"(已用优惠券，实付"+payment_cal+"元)");

                    }
                    else
                    {
                        tv_money.setText(dayPriceList.get(options1).getAmount()+"元");
                        payment_cal = dayPriceList.get(options1).getAmount();
                    }
                }
                else
                {
                    tv_money.setText(dayPriceList.get(options1).getAmount()+"元");
                    payment_cal = dayPriceList.get(options1).getAmount();
                }

            }
        });
    }


    /**
     * 设置地址
     *
     * @param provinceList
     */
    private void setAddress(List<AreaBean> provinceList) {
        AddressSelector selector = new AddressSelector(this);
        selector.setAddressProvider(new TestAddressProvider(provinceList, MessagePublishActivity.this));

        final BottomDialog dialog = new BottomDialog(this);
        selector.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(chihane.jdaddressselector.model.Province province, chihane.jdaddressselector.model.City city, County county, Street street) {
                String s =
                        (province == null ? "" : province.name) +
                                (city == null ? "" : " " + city.name) +
                                (county == null ? "" : " " + county.name) +
                                (street == null ? "" : " " + street.name);
                if (street != null) {
                    Province = province.name;
                    City = city.name;
                    district = county.name;
                    MessagePublishActivity.this.street = street.name;
                    tv_position.setText(s);
                }
                dialog.cancel();
            }
        });
        ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.addContentView(selector.getView(), layout);
        dialog.show();
    }


    @OnClick({R.id.iv_back, R.id.tv_service_type, R.id.tv_publish_time, R.id.tv_position, R.id.tv_money, R.id.tv_title, R.id.tv_content,R.id.tv_publish,R.id.iv_add_pic,R.id.tv_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_service_type:
                Intent intent = new Intent(MessagePublishActivity.this,ShareMessageClassifyActivity.class);
                intent.putExtra("origin",MessagePublishActivity.class.getName());
                startActivityForResult(intent, REQUEST_TYPE);
                break;
            case R.id.tv_publish_time:
                if (dayList.size() == 0)
                {
                    getPrice();
                }
                else
                {
                    showPickDialog();
                }
                break;
            case R.id.tv_position:
                /*Intent positionIntent = new Intent(MessagePublishActivity.this, PositionActivity.class);
                positionIntent.putExtra("origin","MessagePublishActivity");
                startActivityForResult(positionIntent,REQUEST_POSITION);*/
                if (provinceList != null && provinceList.size() != 0) {
                    setAddress(provinceList);
                } else {
                    /*dataManager = new DataManager();
                    observerOnNextListener = new ObserverOnNextListener<List<AreaBean>>() {
                        @Override
                        public void onNext(List<AreaBean> provinceBeanList) {
                            provinceList = provinceBeanList;
                            setAddress(provinceList);
                        }
                    };
                    dataManager.getAreaAllProvince(new ProgressObserver<List<AreaBean>>(observerOnNextListener, this), new HashMap<String, String>());*/

                    GetPositionUtil.getPosition(MessagePublishActivity.this, "", new GetPositionUtil.SearchResult() {
                        @Override
                        public void onResult(DistrictResult districtResult) {

                        }

                        @Override
                        public void onListResult(List<AreaBean> list) {
                            provinceList = list;
                            setAddress(provinceList);
                        }
                    });
                }
                break;
            case R.id.tv_money:

                break;
            case R.id.tv_title:
                Intent titleIntent = new Intent(MessagePublishActivity.this,ShareMessageInputActivity.class);
                titleIntent.putExtra("origin","title");
                titleIntent.putExtra("content",title);
                titleIntent.putExtra("limit",100);
                startActivityForResult(titleIntent,REQUEST_TITLE);
                break;
            case R.id.tv_content:
                Intent describeIntent = new Intent(MessagePublishActivity.this,ShareMessageInputActivity.class);
                describeIntent.putExtra("origin","describe");
                describeIntent.putExtra("content",content);
                describeIntent.putExtra("limit",300);
                startActivityForResult(describeIntent,REQUEST_DESCRIBE);
                break;
            case R.id.tv_phone:
                Intent phoneIntent = new Intent(MessagePublishActivity.this,ShareMessageInputActivity.class);
                phoneIntent.putExtra("origin","phone");
                phoneIntent.putExtra("content",phone);
                phoneIntent.putExtra("limit",11);
                startActivityForResult(phoneIntent,REQUEST_PHONE);
                break;
            case R.id.tv_publish:

                if (topicid == 0)
                {
                    ToastUtils.show(MessagePublishActivity.this,"请选择发布类型");
                    return;
                }

                if (TextUtils.isEmpty(duration))
                {
                    ToastUtils.show(MessagePublishActivity.this,"请选择发布天数");
                    return;
                }

                if (TextUtils.isEmpty(content))
                {
                    ToastUtils.show(MessagePublishActivity.this,"请输入信息详情");
                    return;
                }
                if (TextUtils.isEmpty(street))
                {
                    ToastUtils.show(MessagePublishActivity.this,"请选择信息位置");
                    return;
                }

                if (TextUtils.isEmpty(phone))
                {
                    ToastUtils.show(MessagePublishActivity.this,"请输入手机号码");
                    return;
                }

                if (selectList.size()>0)
                {
                    uploadImage();
                }
                else
                {
                    publishData();
                }
                break;
            case R.id.iv_add_pic:
                DisplayUtil.openAlbum(MessagePublishActivity.this, 8, selectList, PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if ("payfinish".equals(messageEvent.getMessage())) {
            finish();
        }
    }
}
